<script lang="ts" setup>
import { otherApi, userApi } from '@/request/api'
import upload from '@/request/upload'
import { useProfile } from '@/stores'
import {
  useChooseImage,
  useConsole,
  useHideLoading,
  useLoading,
  useModal,
  useNavBack,
  useToast,
} from '@/utils'
import { useAlipayIDCardOCR } from '@/utils/ocr'
import { onLoad } from '@dcloudio/uni-app'
import { to } from 'await-to-js'
import { isArrayLikeObject, isEmpty, isNil } from 'lodash-es'
import { ref } from 'vue'
import { array as zarray, object as zobject, string as zstring } from 'zod'

const profiel = useProfile()

const image1 = ref('')
const image2 = ref('')
const image3 = ref('')
const name = ref('')
const idCard = ref('')
const email = ref('')
//
const verIfyType = ref<boolean>(true)
onLoad(() => {
  if (isArrayLikeObject(profiel.userInfo.idCardUrl)) {
    const { idCardUrl } = profiel.userInfo
    image1.value = idCardUrl[0] ?? ''
    image2.value = idCardUrl[1] ?? ''
    image3.value = idCardUrl[2] ?? ''
  }
  /** 快手端 并且是wohe 隐藏身份证 邮箱，身份证传默认oss */
  if (PRODUCT_ENV === 'youxiang' && UNI_PLATFORM === 'mp-kuaishou') {
    verIfyType.value = false
  }
  name.value = profiel.userInfo.name ?? ''
  idCard.value = profiel.userInfo.idCard ?? ''
  email.value = profiel.userInfo.email ?? ''
})

async function handleChooseImage(
  type: 1 | 2 | 3,
  pluginData?: Record<string, any>,
) {
  // 需要 OCR 识别：人像面
  if (type === 1) {
    // #ifdef MP-ALIPAY
    await (async () => {
      const [ocrErr, ocrRes] = await to(
        useAlipayIDCardOCR({ bizId: '身份证', type: 'FRONT' }),
      )
      if (ocrErr) {
        return
      }
      useConsole?.log(ocrRes)
      useLoading(true)
      const [uploadErr, uploadRes] = await to(
        upload({ filePath: ocrRes.image }),
      )
      useHideLoading()
      if (uploadErr) {
        return
      }

      image1.value = uploadRes.fileUrl
      name.value = ocrRes.data.name.data
      idCard.value = ocrRes.data.num.data
    })()
    // #endif

    // #ifdef MP-WEIXIN
    await (async () => {
      if (isNil(pluginData)) {
        return
      }
      useConsole?.log('pluginData', pluginData)

      useLoading(true)
      const [uploadErr, uploadRes] = await to(
        upload({ filePath: pluginData.detail.image_path }),
      )
      useHideLoading()
      if (uploadErr) {
        return
      }

      image1.value = uploadRes.fileUrl
      name.value = pluginData.detail.name.text
      idCard.value = pluginData.detail.id.text
    })()
    // #endif

    // #ifdef H5
    await (async () => {
      const [chooseErr, chooseRes] = await to(useChooseImage())
      if (chooseErr) {
        return
      }

      useLoading(true)
      const [uploadErr, uploadRes] = await to(
        upload({ filePath: chooseRes[0] }),
      )
      useHideLoading()
      if (uploadErr) {
        return
      }

      useLoading(true)
      const [apiErr, apiRes] = await to(
        otherApi.ocrCheck({ faceUrl: uploadRes.fileUrl }),
      )
      useHideLoading()
      if (apiErr) {
        return
      }

      image1.value = uploadRes.fileUrl
      name.value = apiRes.faceInfo.name
      idCard.value = apiRes.faceInfo.num
    })()
    // #endif
    // #ifdef  MP-KUAISHOU
    await (async () => {
      const [chooseErr, chooseRes] = await to(
        useChooseImage({
          count: 1,
          mediaType: ['image'],
          sourceType: ['album', 'camera'],
        }),
      )
      useConsole?.log('chooseErr', chooseRes)
      if (chooseErr) {
        return
      }

      useLoading(true)
      const [uploadErr, uploadRes] = await to(
        upload({ filePath: chooseRes[0] }),
      )
      useHideLoading()
      if (uploadErr) {
        return
      }

      image1.value = uploadRes.fileUrl
    })()
    // #endif
  }
  // 不需要 OCR 识别
  else {
    const option: any = {
      // #ifdef  MP-KUAISHOU
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      // #endif
    }
    const [chooseErr, chooseRes] = await to(useChooseImage(option))

    if (chooseErr) {
      return
    }

    const [uploadErr, uploadRes] = await to(upload({ filePath: chooseRes[0] }))
    if (uploadErr) {
      return
    }

    // 国徽面
    if (type === 2) {
      image2.value = uploadRes.fileUrl
    }
    // 手持照
    else if (type === 3) {
      image3.value = uploadRes.fileUrl
    }
  }
}

async function handleSubmit() {
  if (profiel.hasRealNameVerified) {
    return
  }
  const body = verIfyType.value
    ? {
        idCardUrl: [image1.value, image2.value, image3.value],
        email: email.value,
        name: name.value,
        idCard: idCard.value,
        contractUserInfo: '',
      }
    : {
        idCardUrl: [
          import.meta.env.VITE_FORM_TEMPLATE_verifry_Hold,
          import.meta.env.VITE_FORM_TEMPLATE_verifry_identity,
          import.meta.env.VITE_FORM_TEMPLATE_verifry_reverse,
        ],
        email: 'xxxx@qq.com',
        name: name.value,
        idCard: idCard.value,
        contractUserInfo: '',
      }
  const zparse = zobject({
    idCardUrl: zarray(
      zstring().startsWith('http', { message: '请上传完整照片' }),
    )
      .length(3)
      .transform(x => JSON.stringify(x)),
    name: zstring().min(2, { message: '请填写完整姓名' }),
    idCard: zstring().regex(/(^\d{15}$)|(^\d{17}(\d|X)$)/, {
      message: '请填写完整身份证号',
    }),
    email: zstring().email({ message: '请填写完整邮箱' }),
    contractUserInfo: zstring(),
  }).safeParse(body)
  if (!zparse.success) {
    useToast(zparse.error.issues[0].message)
    return
  }
  useLoading(true)
  const [err] = await to(userApi.saveidCardImage(zparse.data))
  useHideLoading()
  if (err) {
    return
  }

  // #ifdef  MP-KUAISHOU
  const userInfo = ks.getStorageSync('userInfo')
  ks.setStorageSync('userInfo', { ...userInfo, ...body })
  profiel.init()
  useNavBack()
  // #endif
  // #ifndef MP-KUAISHOU
  useProfile().updateItems(body)
  await useModal({
    title: '温馨提示',
    content: '实名认证成功',
    showCancel: false,
    confirmText: '返回',
  })
  useNavBack()
  // #endif
}
</script>

<template>
  <view class="px-30px py-20px">
    <!--  -->
    <view v-if="verIfyType" class="rd-16px bg-white px-20px pb-20px">
      <view class="text-theme-primary pl-10px text-28px lh-70px">请使用本人真实有效的身份证照片</view>
      <view class="grid grid-cols-3 gap-x-5px">
        <view class="relative" @click="handleChooseImage(1)">
          <ui-aspect-ratio :ratio="1.58353">
            <image
              v-if="isEmpty(image1)"
              class="h-full w-full rd-10px"
              src="~@/static/verify/1.png"
              mode="aspectFill"
            ></image>
            <image
              v-else
              class="h-full w-full rd-10px"
              :src="image1"
              mode="aspectFill"
            ></image>
          </ui-aspect-ratio>
          <!-- #ifdef MP-WEIXIN -->
          <view class="absolute top-0 h-full w-full overflow-hidden">
            <wechat-orc
              certificate-type="idCard"
              :opposite="false"
              @on-success="handleChooseImage(1, $event)"
            >
              <view class="h-200px w-300px"></view>
            </wechat-orc>
          </view>
          <!-- #endif -->
        </view>
        <view class="relative" @click="handleChooseImage(2)">
          <ui-aspect-ratio :ratio="1.58353">
            <image
              v-if="isEmpty(image2)"
              class="h-full w-full rd-10px"
              src="~@/static/verify/2.png"
              mode="aspectFill"
            ></image>
            <image
              v-else
              class="h-full w-full rd-10px"
              :src="image2"
              mode="aspectFill"
            ></image>
          </ui-aspect-ratio>
        </view>
        <view class="" @click="handleChooseImage(3)">
          <ui-aspect-ratio :ratio="1.58353">
            <image
              v-if="isEmpty(image3)"
              class="h-full w-full rd-10px"
              src="~@/static/verify/3.png"
              mode="aspectFill"
            ></image>
            <image
              v-else
              class="h-full w-full rd-10px"
              :src="image3"
              mode="aspectFill"
            ></image>
          </ui-aspect-ratio>
        </view>
      </view>
    </view>

    <!--  -->
    <view class="mt-10px rd-16px bg-white px-20px">
      <!-- <view class="text-theme-primary pl-10px pt-21px text-28px">注意：若信息识别有误请编写修正</view> -->
      <view class="flex items-center px-10px">
        <view class="text-24px text-#3 lh-90px form-item-important-mark">证件姓名</view>
        <input
          v-model="name"
          type="text"
          class="h-90px flex-1 text-right text-24px lh-90px"
          maxlength="20"
          placeholder="请输入证件姓名"
        >
      </view>
      <view class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px">
        <view class="text-24px text-#3 lh-90px form-item-important-mark">证件号码</view>
        <input
          v-model="idCard"
          type="text"
          class="h-90px flex-1 text-right text-24px lh-90px"
          maxlength="18"
          placeholder="请输入证件号码"
        >
      </view>
      <view
        v-if="verIfyType"
        class="flex items-center b-t-1px b-t-#e0 b-t-solid px-10px"
      >
        <view class="text-24px text-#3 lh-90px form-item-important-mark">邮箱地址</view>
        <input
          v-model="email"
          type="text"
          class="h-90px flex-1 text-right text-24px lh-90px"
          maxlength="50"
          placeholder="请填写"
        >
      </view>
    </view>

    <view class="mt-10px rd-16px bg-white px-20px pb-20px">
      <view class="text-theme-primary pl-10px text-28px lh-70px">须知</view>
      <view class="text-24px text-gray-400">
        <view v-if="verIfyType" class="lh-[1.5]">1.身份证为大陆公民持有的本人二代身份证<br>2.请确保身份证边框完整，字体清晰，证件号码清晰可见</view>
        <image
          v-if="verIfyType"
          class="mt-15px w-full"
          src="~@/static/verify/tip.jpg"
          mode="widthFix"
        ></image>
        <view class="mt-15px lh-[1.5]">根据平台规定，租赁商品需要提供下单人的实名信息，{{
          verIfyType
            ? "上传身份证照片主要用于核验的您的身份证件信息与下单账号的身份信息是否一致，以及您提交的租赁订单是否出于您的真实意愿，请您配合进行实名认证，以确保交易双方的安全"
            : "身份证信息必须一致，以及您提交的租赁订单是否出于您的真实意愿，请您配合，以确保交易双方的安全"
        }}</view>
      </view>
    </view>
  </view>

  <view class="fixed bottom-0 w-full flex bg-white pt-15px safe-pb-15px">
    <view
      class="btn-primary-black mx-a w-600px text-36px lh-80px"
      :class="profiel.hasRealNameVerified ? 'bg-gray color-white' : ''"
      @click="handleSubmit"
    >提交
    </view>
  </view>
</template>

<style lang="less" scoped></style>
